
import 'package:dio/dio.dart';
import 'package:flutter_common_app/api/base_api.dart';
import 'package:loading_more_list/loading_more_list.dart';
import 'common_util/log_util.dart';

typedef List<T> ListBuilder<T>(List<dynamic> list);

class CommonPageLoadController<T> extends LoadingMoreBase<T> {
  CommonPageLoadController(
    this.baseApi,
    this.listBuilder, {
    this.count = 10,
    this.isStartLoad = true,
    this.requestCallback,
  });

  BaseApi baseApi;

  int _pageIndex = 1;

  int count;

  bool _hasMore = true;

  bool forceRefresh = false;

  ListBuilder<T> listBuilder;

  //是否立即加载
  bool isStartLoad;
  Function requestCallback;

  int get pageIndex {
    return _pageIndex;
  }

  @override
  bool get hasMore {
    return _hasMore;
  }

  @override
  Future<bool> refresh([bool notifyStateChanged = false]) async {
    _hasMore = true;
    _pageIndex = 1;

    // notifyStateChanged 为 false 时，不会自动清除数据，需要手机清除一下
    if (!notifyStateChanged) {
      clear();
    }

    var result = await super.refresh(notifyStateChanged);
    return result;
  }

  @override
  Future<bool> loadData([bool isLoadMoreAction = false]) async {
    bool isSuccess = false;
    if (isStartLoad) {
      try {
        Response response = await baseApi.send();
        if (response.data['code'] != 200) {
          _hasMore = false;
          isSuccess = true;
        } else {
          List<dynamic> dataList = [];
          dataList = response.data['data'];
          LogUtil.v('测试输出${dataList.length}');

          this.addAll(listBuilder(dataList));
          if (dataList.length == count) {
            _hasMore = true;
          } else {
            _hasMore = false;
          }

          _pageIndex++;
          isSuccess = true;
        }
      } catch (e) {
        LogUtil.v('CommonPageLoadController->e: $e');
        isSuccess = false;
      }
    } else {
      isStartLoad = false;
      isSuccess = true;
    }

    if (requestCallback != null) {
      requestCallback(isSuccess);
    }
    return isSuccess;
  }
}
